//
//  PicViewController.m
//  used
//
//  Created by lanou on 16/7/21.
//  Copyright © 2016年 王凯. All rights reserved.
//

#import "YSLPicViewController.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface YSLPicViewController ()<UINavigationControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>

@property (nonatomic, strong)baseView *baseView;

@property (nonatomic, strong)base2View *base2View;
@property (nonatomic,strong)NSMutableArray * imgArr;// 用来存取选取的照片

@property (nonatomic,strong)UICollectionView * cv;

@property (nonatomic,strong)UIView * background;


@property (nonatomic, copy) NSString *province;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, strong)MBProgressHUD *hub;

@end

@implementation YSLPicViewController

//懒加载
- (MBProgressHUD *)hub {
    
    if (!_hub) {
        _hub = [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:_hub];
    }
    return _hub;
}

- (baseView *)baseView {

        if (!_baseView) {
            _baseView = [[NSBundle mainBundle] loadNibNamed:@"baseView" owner:nil options:nil].lastObject;
            
            _baseView.frame = CGRectMake(0, 64, kWidth, kWidth * 0.5);
            [_baseView.sortBtn addTarget:self action:@selector(sortAction) forControlEvents:UIControlEventTouchUpInside];
        }
    return _baseView;
}

- (void)sortAction {
    __weak YSLPicViewController *weakSelf = self;
    KLCataListViewController *cateVc = [[KLCataListViewController alloc] init];
    cateVc.block = ^(NSString *address){
        weakSelf.baseView.SortText.text = address;
    };
    [self.navigationController pushViewController:cateVc animated:YES];
}

- (base2View *)base2View {

    if (!_base2View) {
        _base2View = [[NSBundle mainBundle] loadNibNamed:@"base2View" owner:nil options:nil].lastObject;
        [_base2View.selectAddressBtn addTarget:self action:@selector(selectAddress) forControlEvents:UIControlEventTouchUpInside];
    }
    return _base2View;
}

- (void)selectAddress {
    
    KLAddressListViewController *addressVc = [[KLAddressListViewController alloc] init];
    __weak YSLPicViewController *weakSelf = self;
    addressVc.block = ^(NSString *province, NSString *city) {
        weakSelf.province = province;
        weakSelf.city = city;
        weakSelf.base2View.address.text = [NSString stringWithFormat:@"%@, %@", province, city];
    };
    [self.navigationController pushViewController:addressVc animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.imgArr = [[NSMutableArray alloc]init];
    
    UIImage * img = [UIImage imageNamed:@"add-img.png"];
    
    [self.imgArr addObject:img];
    
    self.view.backgroundColor= KLRGBColor(244, 244, 244);

    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(returnItem)];
    
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(upLoad)];
    
    [self createUI];
    
    [self setTextField];
    
    
}

- (void)upLoad {
    
    NSString *goodsname = self.baseView.titleText.text;
    NSInteger salePrice = [self.base2View.buyText.text integerValue];
    NSString *sort = self.baseView.SortText.text;
    NSString *desc = self.baseView.describeText.text;
    NSString *address = self.base2View.address.text;
    NSInteger originPrice = [self.base2View.moneyText.text integerValue];

    if ([goodsname isEqualToString:@""]) {
        [self showMessage:@"请输入标题"];
    }else if ([sort isEqualToString:@""]) {
        [self showMessage:@"请选择一个分类"];
    }else if ([desc isEqualToString:@""]) {
        [self showMessage:@"请给物品一个描述"];
    }else if ([address isEqualToString:@"位置获取中"]) {
        [self showMessage:@"请选择您当前的位置"];
    }else if (originPrice == 0) {
        [self showMessage:@"请给商品一个价格"];
    }else if (salePrice == 0) {
        [self showMessage:@"请给商品一个价格"];
    }else {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定发布" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            self.hub.labelText = @"正在努力的上传...";
            [self.hub show:YES];
            
            __weak YSLPicViewController *weakSelf = self;
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                // 创建BmobObject对象，指定对应要操作的数据表名称
                BmobObject *publish = [[BmobObject alloc]initWithClassName:@"Publish"];
                // 获取当前用户
                BmobUser *user = [BmobUser getCurrentUser];
                // 设置字段值
                [publish setObject:user forKey:@"user"];
                [publish setObject:goodsname forKey:@"goodsname"];
                [publish setObject:sort forKey:@"sort"];
                [publish setObject:desc forKey:@"desc"];
                [publish setObject:self.province forKey:@"province"];
                [publish setObject:self.city forKey:@"city"];
                [publish setObject:@(salePrice) forKey:@"salePrice"];
                [publish setObject:@(originPrice) forKey:@"oringePrice"];
                
                //     上传图片
                NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
                NSMutableArray *dataimages = [NSMutableArray array];
                NSMutableArray *filepaths = [NSMutableArray array];
                
                for (int i = 0; i < self.imgArr.count; i++) {
                    // 压缩图片
                    UIImage *image = [[ChangeImageSize defaultManager] imageCompressForSize:self.imgArr[i] targetSize:CGSizeMake(300, 300)];
                    NSData *data = UIImagePNGRepresentation(image);
                    [dataimages addObject:data];
                    
                    
                    NSString *fileString = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png", i]];
                    [data writeToFile:fileString atomically:YES];
                    [filepaths addObject:fileString];
                }
                
                BmobObject *image = [[BmobObject alloc] initWithClassName:@"images"];
                [BmobFile filesUploadBatchWithPaths:filepaths progressBlock:^(int index, float progress) {
                    
                    NSLog(@"%d---%f", index,progress);
                    
                } resultBlock:^(NSArray *array, BOOL isSuccessful, NSError *error) {
                    
                    for (int i = 0 ; i < array.count ;i ++) {
                        BmobFile *file = array [i];
                        NSString *key = [NSString stringWithFormat:@"image%d",i];
                        [image setObject:file  forKey:key];
                    }
                    [image saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                        if (isSuccessful) {
                            [publish setObject:image forKey:@"imageurl"];
                            [publish saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                                if (isSuccessful){
                                    
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        
                                        weakSelf.hub.labelText = @"上传成功!";
                                        weakSelf.hub.mode = MBProgressHUDModeText;
                                        [weakSelf.hub showAnimated:YES whileExecutingBlock:^{
                                            sleep(1);
                                        } completionBlock:^{
                                            [self.hub removeFromSuperViewOnHide];
                                            self.hub = nil;
                                         
                                            [weakSelf dismissViewControllerAnimated:YES completion:nil];
                                        }];
                                    });
                                    
                                }else {
                                    NSLog(@"%@", error);
                                }
                            }];
                        }
                    }];
                }];
                
                
            });
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }
 
}


- (void)showMessage:(NSString *)message {
    self.hub.labelText = message;
    self.hub.mode = MBProgressHUDModeText;
    [self.hub showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [self.hub removeFromSuperViewOnHide];
        self.hub = nil;
    }];

}


//设置键盘
- (void)setTextField
{

    self.baseView.titleText.delegate = self;
    self.baseView.SortText.enabled = NO;

    self.base2View.moneyText.delegate = self;
    self.base2View.buyText.delegate = self;
}

//回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)createUI{

//    self.titleText=[[UITextField alloc]initWithFrame:CGRectMake(20, 320, WIDTH-40, 80)];
//    self.titleText.font = [UIFont systemFontOfSize:15];
//    self.titleText.borderStyle = UITextBorderStyleRoundedRect;
//    
//    [self.view addSubview:self.titleText];
    
    self.baseView.backgroundColor = [UIColor colorWithRed:244.0/255 green:244.0/255 blue:244.0/255 alpha:1];
    
    self.base2View.backgroundColor = [UIColor colorWithRed:244.0/255 green:244.0/255 blue:244.0/255 alpha:1];
    [self.view addSubview:self.baseView];

    
   
    UICollectionViewFlowLayout * fl = [[UICollectionViewFlowLayout alloc]init];
    fl.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.cv = [[UICollectionView alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(self.baseView.frame) + 10, WIDTH -40,kWidth * 0.3 ) collectionViewLayout:fl];
    self.cv.backgroundColor= self.view.backgroundColor;
    
    
    self.cv.delegate = self;
    self.cv.dataSource = self;
    
    [self.cv registerClass:NSClassFromString(@"YSLSelectedCell") forCellWithReuseIdentifier:@"cell"];
    
//    [self.cv registerNib:[UINib nibWithNibName:@"YSLSelectedAddCell" bundle:nil] forCellWithReuseIdentifier:@"addCell"];

    [self.view addSubview:self.cv];
    _base2View.frame = CGRectMake(0, CGRectGetMaxY(self.cv.frame)+ 10, WIDTH, 300);
    [self.view addSubview:self.base2View];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat w = (WIDTH-40)/6-5;
    
    return CGSizeMake(w, w);
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.imgArr.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    YSLSelectedCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.iv.image = self.imgArr[indexPath.row];
    
    if (indexPath.row != self.imgArr.count-1) {
        
        cell.iv.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        
        cell.iv.tag =  100+indexPath.row;
        
        [cell.iv addGestureRecognizer:tapGesture];
        
    }
    return cell;
    
}



- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 5;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == self.imgArr.count -1) {
    
        [self toChoose];
       
    }
}


- (void)toChoose{
    
    SGImagePickerController * picker = [[SGImagePickerController alloc]init];
    
    [picker setDidFinishSelectImages:^(NSArray *array) {
        
    }];
    
    [picker setDidFinishSelectThumbnails:^(NSArray *array) {
        // 给图片数组赋值
        self.imgArr = [NSMutableArray arrayWithArray:array];
        [self.cv reloadData];
    }];
    
    [self presentViewController:picker animated:YES completion:nil];
}



- (void)tapAction:(UITapGestureRecognizer*)sender{
    
    // NSLog(@"%ld",[sender view].tag);
    UIImageView * iv = (UIImageView*)[sender view];
    
    UIImage * img = iv.image;
    
    //创建一个黑色背景
    _background = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH , HEIGHT)];
    
    [ _background setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview: _background];
    
    
    CGFloat h = WIDTH*img.size.height/img.size.width;

    //创建显示图像的视图
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (HEIGHT-h)/2, WIDTH, h)];
    //要显示的图片，即要放大的图片
    imgView.image = img;
    [ _background addSubview:imgView];
    
    imgView.userInteractionEnabled = YES;
    //添加点击手势（即点击图片后退出全屏）
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
    [imgView addGestureRecognizer:tapGesture];
    
    [self shakeToShow: _background];//放大过程中的动画
    
}

-(void)closeView{
    self.navigationController.navigationBarHidden = NO;
    [_background removeFromSuperview];
}
//放大过程中出现的缓慢动画
- (void) shakeToShow:(UIView*)aView{
    
    self.navigationController.navigationBarHidden = YES;
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.1;
    NSMutableArray *values = [NSMutableArray array];
    //  [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}



- (void)returnItem
{
    
   [self dismissViewControllerAnimated:YES completion:nil];
}



@end
